package com.quick.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @ClassName SlaveDataSourceConfig
 * @Description TODO
 * @Author wangxin43
 * @Date 2018/7/3 上午11:45
 * @Version 1.0
 **/
@Configuration
@EnableConfigurationProperties
public class SlaveDataSourceConfig {
    @Bean(name = "slaveDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.slave")
    public DataSource slaveDataSource() {
        DruidDataSource queryDataSource = new DruidDataSource();
        queryDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        queryDataSource.setTestWhileIdle(true);
        queryDataSource.setTestOnReturn(false);
        queryDataSource.setTestOnBorrow(false);
        queryDataSource.setMaxWait(15000);
        queryDataSource.setTimeBetweenEvictionRunsMillis(60000);
        queryDataSource.setPoolPreparedStatements(false);
        queryDataSource.setValidationQuery("select 1 ");
        queryDataSource.setMaxActive(80);
        queryDataSource.setInitialSize(20);
        return queryDataSource;
    }

    @Bean(name = "slaveSqlSessionFactory")
    public SqlSessionFactory slaveSqlSessionFactory(@Qualifier("slaveDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/master/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "slaveTransactionManager")
    public DataSourceTransactionManager slaveTransactionManager(@Qualifier("slaveDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "slaveSqlSessionTemplate")
    public SqlSessionTemplate slaveSqlSessionTemplate(@Qualifier("slaveSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
